package com.yingside.net.chat3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Server {

    private Map<String,ServerThread> map = new HashMap<>();

    public static void main(String[] args)  {
        Server server = new Server();
        server.init();
    }

    public void init(){

        try{
            //端口号不能超过65535，最好不要低于1024
            ServerSocket ss = new ServerSocket(8888);

            while(true){
                //接收客户端的连接
                Socket socket = ss.accept();
                System.out.println(socket.getInetAddress() + ":" + socket.getPort());

                ServerThread st = new ServerThread(socket);
                Thread t = new Thread(st);
                t.start();
            }
        } catch(Exception e){
            e.printStackTrace();
        }

    }

    public class ServerThread implements Runnable{

        private Socket s;
        private BufferedReader br = null;
        private PrintWriter serverOut = null;
        private boolean flag = true;
        private String name;

        public ServerThread(Socket s) throws IOException {
            this.s = s;
            br = new BufferedReader(new InputStreamReader(
                    this.s.getInputStream()
            ));
            serverOut = new PrintWriter(this.s.getOutputStream(),true);
            name = s.getInetAddress() + ":" + s.getPort();
            map.put(name, this);
        }

        //发送信息
        public void send(String msg){
            Set<String> sets = map.keySet();
            for (String address:sets) {
                ServerThread serverThread = map.get(address);
                serverThread.serverOut.println(msg);
            }
        }

        //关闭客户端
        public void stop(String address){
            flag = false;
            map.remove(address);
        }

        public void receive() throws IOException {
            String s = null;
            while((s=br.readLine()) != null){
                if(s.equals("exit")){
                    stop(name);
                    serverOut.println("exit");
                    break;
                }
                System.out.println("服务器端打印:" + s);
                send("服务器端反馈:" + s);
            }
        }
        @Override
        public void run() {
            try {
                receive();
            } catch (IOException e) {
                stop(name);
                e.printStackTrace();
            }
        }
    }


}
